package com.song.osclient.view;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.song.osclient.App;
import com.song.osclient.qrcode.AutoFocusManager;

import java.util.List;

/**
 * use decrypted Api mCamera
 */
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
    private Camera mCamera;
    private SurfaceHolder mHolder;
    private AutoFocusManager autoFocusManager;

    public CameraView(Context context) {
        super(context);
        init();
    }

    public CameraView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CameraView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mHolder = getHolder();
        mHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mCamera = Camera.open();
        } catch (Exception e) {
            e.printStackTrace();
            PrintToast.print("相机打开失败");
            ((Activity) getContext()).finish();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (mHolder.getSurface() == null) {
            return;
        }
        try {
            mCamera.setDisplayOrientation(90);
            mCamera.setPreviewDisplay(mHolder);
            setPreviewSize();
            mCamera.startPreview();
            autoFocusManager = new AutoFocusManager(mCamera);
            if (listener != null) {
                listener.initSuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        release();
        autoFocusManager.stop();
    }

    private void setPreviewSize() {
        if (mCamera == null) return;
        Camera.Parameters parameters = mCamera.getParameters();
        Camera.Size cameraSize = getOptimalPreviewSize(parameters.getSupportedPreviewSizes(), App.getScreenHeight(), App.getScreenWidth());
        Camera.Size pictureSize = getOptimalPreviewSize(parameters.getSupportedPictureSizes(), App.getScreenHeight(), App.getScreenWidth());
        parameters.setPreviewSize(cameraSize.width, cameraSize.height);
        parameters.setPictureSize(pictureSize.width, pictureSize.height);
        mCamera.setParameters(parameters);
    }

    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - h) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - h);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - h) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - h);
                }
            }
        }
        return optimalSize;
    }

    public void capture(Camera.PictureCallback callback) {
        if (mCamera != null)
            mCamera.takePicture(null, null, callback);
    }

    public void stopPreview() {
        if (mCamera != null)
            mCamera.stopPreview();
    }

    public void setPreviewCallback(Camera.PreviewCallback callback) {
        if (mCamera != null) {
            mCamera.setPreviewCallback(callback);
        }
    }

    public void release() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    InitListener listener;

    public void setInitListener(InitListener listener) {
        this.listener = listener;
    }

    public interface InitListener {
        void initSuccess();
    }
}
